<?php

namespace app\common\model;

use app\common\Base;
use think\Model;

class Question extends Model
{
    //引入特性
    use Base;
    //关联分类表
    protected function queToCate()
    {
        return $this->belongsTo('Cate','cid');
    }
    //关联用户表
    protected function queToUser()
    {
        return $this->belongsTo('User','uid');
    }
    //关联答案表
    protected function queToAns()
    {
        return $this->hasMany('Answer','qid');
    }

    //查询问题
    public function getQueList($arr)
    {
        $offset = $arr['offset'] ?? 0;
        $limit = $arr['limit'] ?? config('api.limit');
        //获取关键字
        $wd = $arr['wd'] ?? '';
        //获取分类
        $cid = $arr['cid'] ?? '';
        $where = [];
        //$andwhere = [];
        //组合关键字条件
        if(!empty($wd)){
            $where[] = ['title','like',"%$wd%"];
        }
        //组合分类条件
        if(!empty($cid)){
            $where[] = ['cid','=',"$cid"];
        }
        //限制最大条数
        $limit = min(config('api.maxlist'),$limit);
        //查询
        $rows = self::where($where)->order('id','desc')->limit($offset,$limit)->selectOrFail();
        //关联用户信息
        foreach($rows as $key => $v){
            $v['user'] = $v->queToUser->user;
            $v['userimg'] = $v->queToUser->pic;
            $v['answers'] = count($v->queToAns);
        }
        return $rows;
    }

    //查询单个问题
    public function getQue($id)
    {
        return $this->getOne($id);
        /*//获取点赞最高的回答
        $answer = $qinfo->queToAns()->order('a_zan','desc')->limit(1)->select();
        //关联最高回答的相关信息
        return $answer;*/
    }

    //查询分类下的所有问题
    public function getCateQues($cid,$arr)
    {
        $rows = pageque($this,$arr,['cid'=>$cid]);
        //$rows = $this->where(['cid'=>$cid])->selectOrFail();
        //关联用户信息
        foreach($rows as $key => $v){
            $v['user'] = $v->queToUser->user;
            $v['userimg'] = $v->queToUser->pic;
            $v['answers'] = count($v->queToAns);
        }
        return $rows;
    }

    //获取某个用户的问题
    public function getUserQue($uid,$arr)
    {
        $rows = pageque($this,$arr,['uid'=>$uid]);
        foreach($rows as $v){
            /*$v['user'] = $v->queToUser->user;
            $v['userimg'] = $v->queToUser->pic;*/
            $v['answers'] = count($v->queToAns);
        }
        return $rows;
    }
}
